package com.summer.framework.core.category;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.summer.framework.base.constant.EnumConstant;
import com.summer.framework.base.constant.StringConstant;
import com.summer.framework.core.i18n.I18nUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 数据字典信息的序列化处理
 *
 * @auther Ice Yang
 * Date 2025/9/30 14:36
 */
public class CategorySerializer extends JsonSerializer<Object> {

    private static final Logger log = LoggerFactory.getLogger(CategorySerializer.class);
    private BeanPropertyWriter writer;
    private String type;
    private String group;

    public void init(BeanPropertyWriter writer, String type,String group) {
        this.writer = writer;
        this.type = type;
        this.group = group;
    }

    @Override
    public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        Object bean = jsonGenerator.currentValue();
        if(writer == null){
            jsonGenerator.writeString("");
            return;
        }
        try {
            Object original = writer.get(bean);
            if(original == null){
                return;
            }
            String key = group + StringConstant.DOT + original.toString();
            String message = I18nUtils.getMessage(key);
            if(key.equals(message)){
                if(CategoryType.CATEGORY.equals(type)){
                    message = CategoryCache.get(key);
                }else{
                    message = EnumConstant.getValue(group,original.toString());
                }
            }
            jsonGenerator.writeString(message);
        }catch (Exception e){
            log.error("deal category property has error",e);
        }
    }
}
